#include "rotateimg.h"
#include <QDir>
#include <QDebug>
RotateImg::RotateImg(QObject *parent) : QObject(parent)
{
}
void RotateImg::transFormImg(string &imgPath, double angle)
{
    Mat img = imread(imgPath);
    if (img.empty()) {
        qDebug() << "Images loaded failed...";
    }
    Mat dst, M;
    int h = img.rows;
    int w = img.cols;
    M = getRotationMatrix2D(Point(w / 2, h / 2), angle, 1.0);//中心的，角度，缩放比例
    double cos = abs(M.at<double>(0, 0));
    double sin = abs(M.at<double>(0, 1));
    int nw = cos * w + sin * h;
    int nh = sin * w + cos * h;
//    int xx = (nw / 2 - w / 2);
//    int yy = (nh / 2 - h / 2);
    //新的旋转中心
    M.at<double>(0, 2) += (nw / 2 - w / 2);
    M.at<double>(1, 2) += (nh / 2 - h / 2);
//    int newX = w / 2 + xx;
//    int newY = h / 2 + yy;
    /*vector<Point2f> vp{ Point2f(550,1079),Point2f(1088,1079) };*/
    addRotatedPoint(M);
    //输入图像，输出图像，变换矩阵，输出尺寸；插值符号，边界像素模式，颜色
    warpAffine(img, dst, M, Size(nw, nh), INTER_LINEAR, 0, Scalar(0, 0, 0));
    std::string id = to_string(idx);
    QString pathRotate="E:\\jointImg\\src2Pic\\rotationImg";
    QDir dir(pathRotate);
    // 检查目录是否存在，如果不存在则创建
    if (!dir.exists())
        dir.mkdir(pathRotate);
    std::string rotatePath2=pathRotate.toLocal8Bit().toStdString();
    std::string rotatePath = rotatePath2+"\\rotation-" + id + ".jpg";
    imwrite(rotatePath, dst);
}
void RotateImg::addRotatedPoint(Mat &M)
{
    // 计算旋转后的像素点位置
    std::vector<cv::Point> originalPoints = pointArr[idx];
    //cv::Mat invRotationMatrix;
    //cv::invertAffineTransform(M, invRotationMatrix);//求逆矩阵
    std::vector<cv::Point> rotatedPoints;
    cv::transform(originalPoints, rotatedPoints, M);
    rotatedpointArr[idx++] = rotatedPoints;
}
